package com.laosg.spring.small.core02.factory.support;

import cn.hutool.core.bean.BeanUtil;
import com.laosg.spring.small.core02.beans.PropertyValue;
import com.laosg.spring.small.core02.beans.PropertyValues;
import com.laosg.spring.small.core02.exception.BeansException;
import com.laosg.spring.small.core02.factory.config.BeanDefinition;
import com.laosg.spring.small.core02.factory.config.BeanReference;

import java.lang.reflect.Constructor;

/**
 * <p>description: some thing </p>
 *
 * @author kevin
 * @date 8/18/21
 */
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory{

    private InstantiationStrategy instantiationStrategy=new CglibSubClazzInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition,Object[] args) throws BeansException {
        Object bean=null;
        try {
            bean = createBeanInstance(beanName, beanDefinition, args);
            applyPropertyValues(beanName,bean,beanDefinition);

        } catch (Exception e) {
            throw new BeansException("instantion of bean fail",e);
        }
        addSingleton(beanName,bean);
        return bean;
    }

    protected void applyPropertyValues(String beanName,Object bean,BeanDefinition beanDefinition) {
        try {
            PropertyValues propertyValues = beanDefinition.getPropertyValues();
            for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
                String name = propertyValue.getName();
                Object value = propertyValue.getValue();
                //这里有bean 依赖 怎么处理？
                if (value instanceof BeanReference) {
                    //先获取到依赖，再赋值
                    BeanReference beanReference = (BeanReference) value;
                    value=getBean(beanReference.getBeanName());
                }
                BeanUtil.setFieldValue(bean,name,value);
            }

        } catch (Exception e) {
            throw new BeansException("Error setting property values "+ beanName);
        }

    }
    protected Object createBeanInstance(String beanName, BeanDefinition beanDefinition,Object[] args) {
        Constructor constructor=null;
        Class beanClass = beanDefinition.getBeanClass();
        Constructor[] declaredConstructors = beanClass.getDeclaredConstructors();
        for (Constructor cto : declaredConstructors) {
            if (null != args && cto.getParameterTypes().length == args.length) {
                constructor=cto;
                break;
            }
        }
        return getInstantiationStrategy().instantiate(beanName,beanDefinition,constructor,args);
    }

    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }

    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }
}
